/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.ifba.eletrica.alertavibracao.ui;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author root
 */
public class UI extends javax.swing.JFrame implements Runnable {

    private static final String WARNING_FILE_PATH = "C:\\..\\WARNING.txt";
    
    private static final String EMAIL_TO = "@mail.com";
    private static final String EMAIL_FROM = "@gmail.com";
    private static final String EMAIL_PASSW = "";
    
    private Thread runner;
    
    /**
     * Creates new form UI
     */
    public UI() {
        initComponents();
        
    }

    public void iniciar() {
        runner = new Thread(this);
        runner.start();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        iconeAlerta = new javax.swing.JLabel();
        lblAcao = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ALERTA DE VIBRAÇÃO");
        setResizable(false);

        iconeAlerta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ifba/eletrica/alertavibracao/ui/alert.png"))); // NOI18N
        iconeAlerta.setEnabled(false);

        lblAcao.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
        lblAcao.setForeground(new java.awt.Color(0, 0, 51));
        lblAcao.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblAcao.setText("MONITORANDO...");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblAcao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(248, 248, 248)
                .addComponent(iconeAlerta)
                .addContainerGap(254, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(iconeAlerta)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblAcao)
                .addContainerGap(189, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel iconeAlerta;
    private javax.swing.JLabel lblAcao;
    // End of variables declaration//GEN-END:variables

    @SuppressWarnings("CallToPrintStackTrace")
    private void sendEmail(String messageBody) {
      Properties properties = System.getProperties();
      properties.put("mail.smtp.port", "587");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.starttls.enable","true");
      properties.setProperty("mail.smtp.host", "smtp.gmail.com");
      Session session = Session.getInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(EMAIL_FROM, EMAIL_PASSW);
      }}); 
        
      try{
         MimeMessage message = new MimeMessage(session);
         message.setFrom(new InternetAddress(EMAIL_FROM));
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(EMAIL_TO));
         message.setSubject("[URGENTE] ALERTA DE DESBALANCEAMENTO!");
         message.setText(messageBody);
         Transport.send(message);
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }    
    }
    
    @SuppressWarnings("CallToPrintStackTrace")
    private String readWarningMessage() {
        String message = "";
        try {
           String currentLine;

            BufferedReader br;
            br = new BufferedReader(new FileReader(WARNING_FILE_PATH));
            while ((currentLine = br.readLine()) != null) {
                    message += currentLine + "\n";
            }
            br.close();
        } catch (Exception e) {
                e.printStackTrace();
        } 
        
        return message;
    } 
    
    @Override
    @SuppressWarnings("SleepWhileInLoop")
    public void run() {
        while (true) {
            
            File warnFile = new File(WARNING_FILE_PATH);
            if (warnFile.canWrite()) {
                iconeAlerta.setEnabled(true);

                lblAcao.setVisible(true);
                lblAcao.setForeground(Color.RED);
                lblAcao.setText(
                        "DESBALANCEAMENTO DETECTADO! ENVIANDO ALERTA...");
                
                sendEmail(readWarningMessage());
            } else {
                lblAcao.setForeground(Color.BLUE);
                lblAcao.setVisible(!lblAcao.isVisible());
                iconeAlerta.setEnabled(false);
            }
            
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(UI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
